import { _decorator, Component, Node, Sprite, resources, SpriteFrame, Animation, AnimationClip, SpriteAtlas, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('LoadAnimation')
export class LoadAnimation extends Component {
    private static _instance: LoadAnimation | null = null;

    // Singleton instance getter
    public static getInstance(): LoadAnimation {
        if (!this._instance) {
            this._instance = new LoadAnimation();
        }
        return this._instance;
    }

    start() {
        // For Singleton usage, this will not be called directly.
    }

    loadAnimation(animation: Animation, spriteAtlasPath: string, startFrame: number, endFrame: number, wrapMode: number, animationState: string, objectName: string, callback: (node: Node) => void) {
        resources.load(spriteAtlasPath, SpriteAtlas, (err, atlas: SpriteAtlas) => {
            if (err) {
                console.log('error here');
                return;
            }

            const frames: SpriteFrame[] = [];
            for (let i = startFrame; i <= endFrame; i++) {
                let frame = atlas.getSpriteFrame(`${i}`);
                if (!frame) break;
                frames.push(frame);
            }

            this.createAnimation(frames, animation, wrapMode, animationState, objectName);
            callback(animation.node);
        });
    }

    createAnimation(frames: SpriteFrame[], animation: Animation, wrapMode: number, animationState: string, objectName: string) {
        let clip = AnimationClip.createWithSpriteFrames(frames, 10);
        clip.name = `${objectName}_${animationState}`;
        clip.wrapMode = wrapMode;

        animation.defaultClip = clip;
        animation.play(`${objectName}_${animationState}`);
    }

    newNode(objectName: string, position: Vec3, startFrame: number, endFrame: number, animationState: string, spriteAtlasPath: string, wrapMode: number): Node {
        let newNode = new Node(objectName);
        newNode.setPosition(position);
        newNode.addComponent(Sprite);
        let animation = newNode.addComponent(Animation);

        this.loadAnimation(animation, spriteAtlasPath, startFrame, endFrame, wrapMode, animationState, objectName, (node: Node) => {
            this.node.addChild(node);
            animation.play();
        });

        console.log("123");

        return newNode;
    }
}
